package service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

import titt.TITT;

public class Connector {

	private Map<String,Set<String>> services = new HashMap<String,Set<String>>();

	private Set<String> updaters = new HashSet<String>();

	private int i = 0;

	public void tittAdded(String[] tokens) {
		System.out.println(Arrays.toString(tokens));
		if(tokens[1].equals("service")) {
			String[] s = tokens[2].split("-");
			services.get(s[0]).add(tokens[2]);
		}
		else {
			updaters.add(tokens[2]);
			services.put(tokens[2], new HashSet<String>());
		}

	}

	public void updateAll() {
		updateAll("");
	}
	
	public void updateAll(String except) {
		String[] sers = getAllServices();
		for(String s : updaters) {
			try {
				if(s.equals(except))
					continue;
				Updater u = TITT.createProxy("connector", "updater", s);
				u.update(sers);
			}
			catch(Exception e) {
				e.printStackTrace();
			}
		}
	}

	public String getID() {
		return ""+i++;
	}

	public void tittRemoved(String[] tokens) {
		if(tokens[1].equals("service")) {
			//			services.remove(tokens[2]);
		}
		else {
			updaters.remove(tokens[2]);
			services.remove(tokens[2]);
			updateAll();
		}
	}

	public void connectionAdded(String from, String to, String argument) {
		
	}
	
	public void connectionRemoved(String from, String to, String argument) {
		
	}
	
	public String[] getAllServices() {
		ArrayList<String> l = new ArrayList<String>();

		for(Set<String> s : services.values())
			l.addAll(s);

		String[] total = new String[l.size()];
		l.toArray(total);

		return total;
	}

}
